package org.inspiration.dudu.web.service.common.impl;

import lombok.RequiredArgsConstructor;
import org.inspiration.dudu.common.util.FileUtil;
import org.inspiration.dudu.common.util.ImageUtil;
import org.inspiration.dudu.user.model.dto.FavoriteFolderDTO;
import org.inspiration.dudu.user.model.dto.UserDTO;
import org.inspiration.dudu.user.service.FavoriteFolderService;
import org.inspiration.dudu.user.service.UserService;
import org.inspiration.dudu.web.service.common.CommonFacadeService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * CommonFacadeServiceImpl 实现类，提供用户登录、注册、图片上传和下载等功能。
 */
@Service
@RequiredArgsConstructor
public class CommonFacadeServiceImpl implements CommonFacadeService {

    private final UserService userService;
    private final FileUtil fileUtil;
    private final ImageUtil imageUtil;
    private final FavoriteFolderService favoriteFolderService;

    /**
     * 用户登录方法
     * 
     * @param userDTO 用户数据传输对象
     * @return 登录结果的字符串
     */
    @Override
    public String login(UserDTO userDTO) {
        return userService.login(userDTO);
    }

    /**
     * 用户注册方法
     * 
     * @param userDTO 用户数据传输对象
     */
    @Override
    @Transactional
    public void register(UserDTO userDTO) {
        userService.register(userDTO);
        Long userId = userService.getUserIdByUsername(userDTO.getUsername());
        // 为用户创建默认收藏夹
        favoriteFolderService.createFavoriteFolder(FavoriteFolderDTO.builder()
                .userId(userId)
                .folderName("默认收藏夹")
                .build());
    }

    /**
     * 图片上传方法
     * 
     * @param file 上传的图片文件
     * @return 包含图片 URL 和状态信息的 Map
     */
    @Override
    public Map<String, Object> uploadImage(MultipartFile file) {
        String url = fileUtil.uploadImage(file);

        // 创建外层 Map
        Map<String, Object> outerMap = new HashMap<>();
        // 设置 errno 字段
        outerMap.put("errno", 0);
        outerMap.put("code", 200);
        // 创建内层 data Map
        Map<String, String> dataMap = new HashMap<>();
        // 设置 url 字段
        dataMap.put("url", url);
        // 设置 alt 字段
        dataMap.put("alt", "alt");
        // 设置 href 字段
        dataMap.put("href", "href");

        // 将 data Map 放入外层 Map
        outerMap.put("data", dataMap);

        return outerMap;
    }

    /**
     * 图片下载方法
     * 
     * @param filename 图片文件名
     * @return 包含图片字节数组的 ResponseEntity
     */
    @Override
    public ResponseEntity<byte[]> downloadImage(String filename) {
        return imageUtil.getImage(filename);
    }
}
